import sys
sys.path.append("../../")
import fitlog
from transformers import DistilBertConfig
from transformers import DistilBertTokenizer
from transformers import BertTokenizer, BertConfig
from datareader import *
from metrics import *
from model import *
import pickle, math
from tqdm import trange
import torch


def DataIter(labeled_source, labeled_target, batch_size=32):
    p_idxs = list(range(len(labeled_source))) if not hasattr(labeled_source, 'valid_indexs') else labeled_source.valid_indexs
    p_len = len(p_idxs)
    if labeled_target is None:
        l_len = 0
        l_idxs = []
    else:
        l_idxs = list(range(len(labeled_target))) if not hasattr(labeled_target, 'valid_indexs') \
            else labeled_target.valid_indexs
        l_len = len(l_idxs)
    data_size = p_len + l_len
    def generator():
        idxs = random.sample(range(data_size), data_size) * 2
        for start_i in range(0, data_size, batch_size):
            batch_idxs = idxs[(start_i):(start_i + batch_size)]
            items = [labeled_source[p_idxs[idx]] if idx < p_len else \
                         labeled_target[l_idxs[idx - p_len]] for idx in batch_idxs]
            yield labeled_source.collate_raw_batch(items)
    return math.ceil(data_size*1.0/batch_size), generator

class SAndTUtils:
    def __init__(self, random_seed):
        self.seed = random_seed
        self.initTrainingEnv()

    def initTrainingEnv(self):
        random.seed(self.seed)
        np.random.seed(self.seed)
        torch.manual_seed(self.seed)
        torch.cuda.manual_seed_all(self.seed)
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False

    def acc_P_R_F1(self, y_true, y_pred):
        return accuracy_score(y_true, y_pred.cpu()), \
                    precision_recall_fscore_support(y_true, y_pred.cpu())

    def Batch2Vecs(self, model: VanillaBert, batch):
        if batch[0].device != model.device:  # data is on a different device
            input_ids, masks, seg_ids = batch[0].to(model.device), \
                                        batch[1].to(model.device), \
                                        batch[2].to(model.device)
        else:
            input_ids, masks, seg_ids = batch[0], batch[1], batch[2]
        encoder_dict = model.bert.bert.forward(
            input_ids=input_ids,
            attention_mask=masks,
            token_type_ids=seg_ids
        )
        return encoder_dict.pooler_output

    def AugBatch2Vecs(self, model:VanillaBert, batch):
        rand = random.random()
        if rand < 0.2:
            model.bert.bert.embeddings.aug_type = "gaussian"
        elif rand < 0.4:
            model.bert.bert.embeddings.aug_type = "g_blur"
        elif rand < 0.6:
            model.bert.bert.embeddings.aug_type = None
            loss, acc = model.lossAndAcc(batch)
            loss.backward()
            model.bert.bert.embeddings.aug_type = "adver"
        elif rand < 0.8:
            model.bert.bert.embeddings.aug_type = "rMask"
        else:
            model.bert.bert.embeddings.aug_type = "rReplace"
        return self.Batch2Vecs(model, batch)

    def lossAndAcc(self, model:VanillaBert, batch, temperature=1.0):
        pooledOutput = self.Batch2Vecs(model, batch)
        logits = model.bert.classifier(pooledOutput)
        preds = F.softmax(logits / temperature, dim=1)
        epsilon = torch.ones_like(preds) * 1e-8
        preds = (preds - epsilon).abs()  # to avoid the prediction [1.0, 0.0], which leads to the 'nan' value in log operation
        labels = batch[-2].to(preds.device)
        labels = labels.argmax(dim=1) if labels.dim() == 2 else labels
        loss = F.nll_loss(preds.log(), labels)
        acc = accuracy_score(labels.cpu().numpy(), preds.argmax(dim=1).cpu().numpy())
        return loss, acc

    def dataset_logits(self, model:VanillaBert, data, idxs=None, batch_size=40):
        preds = []
        if idxs is None:
            idxs = list(range(len(data)))
        for i in trange(0, len(idxs), batch_size):
            batch_idxs = idxs[i:min(len(idxs), i + batch_size)]
            batch = data.collate_raw_batch([data[idx] for idx in batch_idxs])
            pred = model.predict(batch, temperature=1.0)
            preds.append(pred)
        pred_tensor = torch.cat(preds)
        return pred_tensor

    def dataset_inference(self, model:VanillaBert, data, idxs=None, batch_size=20):
        pred_tensor = self.dataset_logits(model, data, idxs, batch_size)
        vals, idxs = pred_tensor.sort(dim=1)
        return idxs[:, -1], vals[:, -1]

    def perf(self, model:VanillaBert, data, label, idxs=None, batch_size=20):
        with torch.no_grad():
            predTensor = self.dataset_logits(model, data, idxs, batch_size)
            _, yPred = predTensor.sort(dim=1)
        yTrue = label[idxs] if idxs is not None else label
        loss = F.nll_loss(predTensor.log(), yTrue.to(predTensor.device))
        return self.acc_P_R_F1(yTrue, yPred[:, -1]) + (loss,)

class SAndT_Trainer(SAndTUtils):
    def __init__(self, random_seed, log_dir, suffix, model_file, class_num, temperature=1.0,
                 learning_rate=5e-3, batch_size=32, grad_accum=1):
        super(SAndT_Trainer, self).__init__(random_seed)
        if os.path.exists(log_dir):
            os.system("rm -r {}".format(log_dir))
        os.system("mkdir {}".format(log_dir))
        fitlog.set_log_dir("{}/".format(log_dir), new_log=True)
        self.log_dir = log_dir
        self.suffix = suffix
        self.model_file = model_file
        self.best_valid_acc = 0.0
        self.min_valid_loss = 1e8
        self.class_num = class_num
        self.temperature = temperature
        self.learning_rate = learning_rate
        self.batch_size = batch_size
        self.valid_step = 0
        self.grad_accum = grad_accum

    def obtainOptim(self, model):
        optimizerGroupedParameters = [
                                         {'params': p,
                                          'lr': self.learning_rate * pow(0.8, 12 - int(
                                              n.split("layer.")[1].split(".", 1)[0])) if "layer." in n \
                                              else (self.learning_rate * pow(0.8, 13) if "embedding" in n else self.learning_rate)
                                          # layer-wise fine-tuning
                                          } for n, p in model.named_parameters()
                                     ]
        optim = torch.optim.Adam(optimizerGroupedParameters)
        return optim


    def ModelTrain(self, trModel : VanillaBert, labeledSource : NLIDataset,
                   labeledTarget : NLIDataset, unlabeledTarget : NLIDataset,
                   validSet : NLIDataset, UT_Label, maxEpoch, validEvery=20):
        print("labeled Source/labeled Target/unlabeled Target: {}/{}/{}".format(len(labeledSource),
                                                                                len(labeledTarget) if labeledTarget is not None else 0,
                                                                                len(unlabeledTarget)))
        optim = self.obtainOptim(trModel)
        validLabel = validSet.labelTensor().clone()
        for epoch in range(maxEpoch):
            maxIters, trainLoader = DataIter(labeledSource, labeledTarget, self.batch_size)
            for step, batch1 in enumerate(trainLoader()):
                try:
                    loss, acc = self.lossAndAcc(trModel, batch1, temperature=self.temperature)
                    trainLoss = loss
                    optim.zero_grad()
                    trainLoss.backward()
                    optim.step()
                    torch.cuda.empty_cache()
                    print("batch1 input shape : ", batch1[0].shape)
                    print('####Model Update (%3d | %3d) %3d | %3d ####, loss = %6.8f, acc = %6.8f' % (
                        step, maxIters, epoch, maxEpoch, loss.data.item(), acc
                    ))
                except:
                    print("batch1 input shape : ", batch1[0].shape)
                    print("batch 1 : \n", batch1)
                    raise
                if (step + 1) % validEvery == 0:
                    rst = self.perf(trModel, validSet, validLabel)
                    acc_v, (p_v, r_v, f1_v, _), loss_v = rst
                    print("valid perf:", rst)
                    output_items = [("valid_acc", acc_v)] + \
                                   [("valid_loss", loss_v)] + \
                                   [('valid_prec_{}'.format(i), p_v[i]) for i in range(self.class_num)] + \
                                   [('valid_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                                   [('valid_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
                    fitlog.add_metric({f"ValidPerf_{self.suffix}": dict(output_items)}, step=self.valid_step)
                    if acc_v > self.best_valid_acc:
                        self.logPerf(trModel, unlabeledTarget, UT_Label, self.suffix, step=0)
                        torch.save(trModel.state_dict(), self.model_file)
                        self.best_valid_acc = acc_v
                    else:
                        self.logPerf(trModel, unlabeledTarget, UT_Label, self.suffix)

    def logPerf(self, model, test_set, test_label, test_suffix, step=-1):
            rst_model = self.perf(model, test_set, test_label)
            acc_v, (p_v, r_v, f1_v, _), loss_v = rst_model
            output_items = [("test_acc", acc_v)] + \
                           [("test_loss", loss_v)] + \
                           [('test_prec_{}'.format(i), p_v[i]) for i in range(self.class_num)] + \
                           [('test_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                           [('test_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
            if step != -1:
                print("BestPerf : ", rst_model)
                fitlog.add_best_metric({f"BestPerf_{test_suffix}": dict(output_items)})
            else:
                print("TestPerf : ", rst_model)
                fitlog.add_metric({f"TestPerf_{test_suffix}": dict(output_items)}, step=self.valid_step)
            self.valid_step += 1

def obtain_model(args, model_device):
    bert_model = 'bert-base-uncased' if args.full_bert else 'distilbert-base-uncased'
    if args.full_bert:
        bert_config = BertConfig.from_pretrained(bert_model, num_labels=2) if args.bertPath is None else \
                        BertConfig.from_pretrained(args.bertPath, num_labels=2)
        tokenizer_M = BertTokenizer.from_pretrained(bert_model) if args.bertPath is None else \
                        BertTokenizer.from_pretrained(args.bertPath)
    else:
        bert_config = DistilBertConfig.from_pretrained(bert_model, num_labels=2) if args.distillBertPath is None else \
                        DistilBertConfig.from_pretrained(args.distillBertPath, num_labels=2)
        tokenizer_M = DistilBertTokenizer.from_pretrained(bert_model) if args.distillBertPath is None else \
                        DistilBertTokenizer.from_pretrained(args.distillBertPath)
    bert_config.num_labels = 3
    bert_config.hidden_act = "relu"
    # Create the model
    if args.full_bert:
        bert = BertForSequenceClassification.from_pretrained(
                        bert_model, config=bert_config).to(model_device) if args.bertPath is None \
                else BertForSequenceClassification.from_pretrained(
                        args.bertPath, config=bert_config).to(model_device)
    else:
        bert = DistilBertForSequenceClassification.from_pretrained(
                    bert_model, config=bert_config).to(model_device) if args.distillBertPath is None \
                else DistilBertForSequenceClassification.from_pretrained(
                        args.distillBertPath, config=bert_config).to(model_device)
    model = VanillaBert(bert).to(model_device)
    return model, tokenizer_M

def obtain_domain_set(new_domain_name, tokenizer_M, lt_count=0):
    SNLI_set = NLIDataset("../../../snli_1.0/snli_1.0_train.jsonl", tokenizer=tokenizer_M)
    testFile = f"../../../multinli_1.0/Domain_{new_domain_name}.jsonl"
    if lt_count != 0:
        filenames = SplitDataFile(testFile, accumulation=[lt_count, -1])
        labeled_target = NLIDataset(filenames[0], tokenizer=tokenizer_M)
        test_set = NLIDataset(filenames[1], tokenizer=tokenizer_M)
    else:
        labeled_target = None
        test_set = NLIDataset(testFile, tokenizer=tokenizer_M)
    val_set = NLIDataset(f"../../../multinli_1.0/fewshot_Domain_{new_domain_name}.jsonl",
                              tokenizer=tokenizer_M, max_data_size=100)
    return SNLI_set, val_set, test_set, labeled_target

def SplitDataFile(fname, accumulation=[0, -1]):
    with open(fname, 'r') as fr:
        lines = [line for line in fr]
    lines = random.sample(lines, len(lines))

    accumulation[-1] = len(lines)
    s = fname.rsplit(".", 1)
    start = 0
    out_file_list = []
    for i, end in enumerate(accumulation):
        sub_file = f"{s[0]}_{i}.{s[1]}"
        with open(sub_file, 'w') as fw:
            fw.write("".join(lines[start:end]))
        out_file_list.append(sub_file)
        start = end
    return out_file_list

def reconfig_args(args):
    args.full_bert = True
    args.bertPath = "../../../bert_en/"

    args.full_bert = True
    print("====>", args.full_bert)
    return args

if __name__ == "__main__":
    with open("../../args.pkl", 'rb') as fr:
        argConfig = pickle.load(fr)
    argConfig.model_dir = str(__file__).rstrip(".py")
    # Set all the seeds
    seed = argConfig.seed
    reconfig_args(argConfig)

    # See if CUDA available
    device = torch.device("cpu") if not torch.cuda.is_available() else torch.device("cuda:0")
    model1_path = "../../saved/modelSNLI_1.pth"

    domainID = 2
    fewShotCnt = 100
    NLIDomainList = list(NLI_domain_map.keys())
    newDomainName = NLIDomainList[domainID-1]

    model1, tokenizer = obtain_model(args=argConfig, model_device=device)
    # tokenizer.model_max_length = 128
    labeledSource, validTarget, unlabeledTarget, labeledTarget = obtain_domain_set(newDomainName,
                                                                                   tokenizer_M=tokenizer,
                                                                                   lt_count=5)
    model1.load_state_dict(torch.load(model1_path))
    trainer = SAndT_Trainer(random_seed=seed, log_dir=argConfig.model_dir, suffix=f"{newDomainName}_FS{fewShotCnt}",
                         model_file=f"{argConfig.model_dir}/SAndT_{newDomainName}_FS{fewShotCnt}",
                         class_num=3, temperature=1.0, learning_rate=5e-5, batch_size=20)
    trainer.ModelTrain(model1, labeledSource, labeledTarget, unlabeledTarget, validTarget,
                       unlabeledTarget.labelTensor().clone(),
                       maxEpoch=1, validEvery=30)